package com.prepowers.cake.service.impl;


import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.prepowers.cake.Config;
import com.prepowers.cake.data.entity.Auth;
import com.prepowers.cake.data.entity.User;
import com.prepowers.cake.data.vo.UserForm;
import com.prepowers.cake.mapper.AuthMapper;
import com.prepowers.cake.mapper.UserMapper;
import com.prepowers.cake.service.UserService;
import com.prepowers.cake.utils.IDGenerator;
import com.prepowers.cake.web.interceptor.AuthUser;


@Service
public class UserServiceImpl implements UserService,UserDetailsService {

	@Autowired
	private Config config;
	
	@Autowired
	private UserMapper uMapper;
		
	@Autowired
	private AuthMapper authMapper;
	
    @Resource(name="userIdGenerator")
    private IDGenerator userIdGen;
    
	@Override
	@Transactional
	public String register(UserForm from) {
		JSONObject rObj = new JSONObject();
		rObj.put("result", "fail");		
		if(from.getNickname() == null || from.getNickname().length() == 0){
			rObj.put("message", "昵称不能为空");
			return rObj.toJSONString();
		}
		if(from.getUsername() == null || from.getUsername().length() == 0){
			rObj.put("message", "用户名不能为空");
			return rObj.toJSONString();
		}
		if(from.getPassword() == null || from.getPassword().length() == 0){
			rObj.put("message", "密码不能为空");
			return rObj.toJSONString();
		}
		if(from.getAvatar() == null || from.getAvatar().length() == 0){
			rObj.put("message", "头像不能为空");
			return rObj.toJSONString();
		}
		User user = new User();
		Long id = userIdGen.nextId();
		user.setId(id);
		user.setNickname(from.getNickname());
		user.setAvatar(from.getAvatar());		
		this.uMapper.save(user);
		
		Auth auth = new Auth();
		auth.setId(userIdGen.nextId());
		auth.setAuth_type_id(1);
		auth.setIdentifier(from.getUsername());
		Md5PasswordEncoder encoder = new Md5PasswordEncoder();
		String encodePassword = encoder.encodePassword(from.getPassword(), config.getSalt());
		auth.setCertify(encodePassword);
		auth.setUser_id(id);
		authMapper.save(auth);
		
		rObj.put("result", "success");
		
		return rObj.toJSONString();
	}

	@Override
	@Transactional
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//		Map<?,?> user = this.uMapper.findByUsername(username);
		if(username == null || username.length() == 0){
			throw new UsernameNotFoundException("用户名不能为空");
		}
		Auth param = new Auth();
		param.setAuth_type_id(1);
		param.setIdentifier(username);
		Auth auth = authMapper.findByAuth(param);
		if(auth != null){
			List<SimpleGrantedAuthority> authorities = new ArrayList<>();
	        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
	        return new AuthUser(auth.getIdentifier(),
	                auth.getCertify(),config.getSalt(), authorities);
		}
		
		if(username.matches("1\\d{10}")){
			param.setAuth_type_id(2);
			param.setIdentifier(username);
			auth = authMapper.findByAuth(param);
			List<SimpleGrantedAuthority> authorities = new ArrayList<>();
	        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
	        System.out.println("username is " + username);
	        new AuthUser(auth.getIdentifier(),
	                auth.getCertify(),config.getSalt(), authorities);			
		}
		throw new UsernameNotFoundException("用户名不能为空"); 
	}

}
